package com.easygo.controller;

import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author 徐策
 * @date 2020/1/15 12:08
 */
@RestController
@Scope("prototype")
public class PageController {

    @GetMapping("/thymeleaf/{msg}")
    public void learn(@PathVariable String msg) throws IOException {

        Random r=new Random();
        int i = r.nextInt(1000);

        User user1=new User("张飞"+i,"address1");
        User user2=new User("马超"+i,"address2");
        User user3=new User("赵云"+i,"address3");
        User user4=new User("曹操"+i,"address4");

        List<User> users=new ArrayList<User>();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);

        //创建模版加载器
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/");  //模板文件的所在目录
        resolver.setSuffix(".html");       //模板文件后缀

        //创建模板引擎
        TemplateEngine templateEngine = new TemplateEngine();
        //将加载器放入模板引擎
        templateEngine.setTemplateResolver(resolver);
        //创建字符输出流并且自定义输出文件的位置和文件名
        FileWriter writer = new FileWriter("D:/html/users"+i+".html");
        //创建Context对象(存放Model)
        Context context = new Context();
        //放入数据
        context.setVariable("data",msg);
        context.setVariable("users",users);
        //创建静态文件,"text"是模板html名字
        templateEngine.process("users",context,writer);
    }


}

class User{

    public User(String name, String address) {
        this.name = name;
        this.address = address;
    }

    private String name;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
